<template>
  <div>
    <img v-if="value" :src="value" style="width:157px;height:84px" @click="openImgdailog()">
    <div v-else class="upBox flex-sc" style="width:157px;height:84px;" @click="openImgdailog(1)">
      <i class="el-icon-plus" style="font-size:25px;color:#C0C4CC" />
    </div>
    <p class="upPicTip">只能上传jpg/png/jpeg文件，且不超过500kb</p>
    <el-dialog v-if="dialogVisible" title="图片剪裁" :visible.sync="dialogVisible" append-to-body :width="diawidth" :show-close="false" @close="closeupimg">
      <el-row type="flex" justify="">
        <label class="el-button el-button--primary" for="uploads" style="margin-right:20px">选择图片</label>
        <input id="uploads" type="file" style="position:absolute; clip:rect(0 0 0 0);" @change="uploadImg($event)">
      </el-row>
      <el-row>
        <div class="cropper-content">
          <div class="cropper" :style="{'width':`${width+50}px`,'height':`${height+50}px`}">
            <vue-cropper
              ref="mycopper"
              :img="option.img"
              :output-size="option.size"
              :output-type="option.outputType"
              :info="true"
              :full="option.full"
              :can-move="option.canMove"
              :can-move-box="option.canMoveBox"
              :original="option.original"
              :auto-crop="option.autoCrop"
              :auto-crop-width="option.autoCropWidth"
              :auto-crop-height="option.autoCropHeight"
              :fixed-box="option.fixedBox"
            />
          </div>
          <!-- 预览框 -->
          <div v-show="false" class="show-preview" :style="{ 'overflow': 'hidden'}">
            <div :style="previews.div" class="preview">
              <img :src="previews.url" :style="previews.img">
            </div>
          </div>
        </div>

      </el-row>
      <div slot="footer">
        <el-button @click="closeupimg">取 消</el-button>
        <el-button type="primary" @click="finish('blob')">确认上传</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
import { api_uploadImg } from '@/api/query'
export default {
  props: {
    value: {
      type: String,
      default: ''
    },
    width: {
      type: Number,
      default: 200
    },
    height: {
      type: Number,
      default: 200
    }
  },
  data() {
    return {
      dialogVisible: false,
      // 剪切图片上传
      crap: false,
      previews: {},
      option: {
        img: '', // 裁剪图片的地址
        // info: true, // 裁剪框的大小信息
        outputSize: 1, // 裁剪生成图片的质量
        outputType: 'png', // 裁剪生成图片的格式
        canScale: false, // 图片是否允许滚轮缩放
        full: false, // 输出原图比例截图 props名full
        canMove: true,
        original: false, // 上传图片按照原始比例渲染
        canMoveBox: true, // 截图框能否拖动
        autoCrop: true, // 是否默认生成截图框
        autoCropWidth: this.width || 200, // 默认生成截图框宽度
        autoCropHeight: this.height || 200, // 默认生成截图框高度
        fixedBox: true, // 固定截图框大小 不允许改变
        fixed: true, // 是否开启截图框宽高固定比例
        fixedNumber: [2, 1], // 截图框的宽高比例
        centerBox: false, // 截图框是否被限制在图片里面
        infoTrue: true // true 为展示真实输出图片宽高 false 展示看到的截图框宽高
      },
      fileName: '', // 本机文件地址
      downImg: '#',
      imgFile: ''

    }
  },
  computed: {
    diawidth() {
      if (this.width > 700) {
        return `${this.width + 150}px`
      } else {
        return '50%'
      }
    }
  },
  methods: {
    openImgdailog() {
      this.dialogVisible = true
    },
    init(val) {
      this.dialogVisible = true
    },
    // 上传图片（点击上传按钮）
    finish(type) {
      this.$showLoading()
      // 输出
      if (type === 'blob') {
        this.$refs.mycopper.getCropBlob((data) => {
          const formData = new FormData()
          // let img = window.URL.createObjectURL(data)
          // this.model = true
          // this.modelSrc = img
          formData.append('file', data, 'image.png')
          api_uploadImg(formData).then((res) => {
            if (res.code === 0) {
              this.$emit('input', this.$baseUrl + res.data)
              this.$message.success(res.msg)
              this.dialogVisible = false
              this.$showLoading('close')
            } else {
              this.$message.error(res.msg)
            }
          })
        })
      } else {
        this.$refs.mycopper.getCropData((data) => {
          console.log(data, 'noblob')
          this.model = true
          this.modelSrc = data
          api_uploadImg(data).then((data) => {
            console.log(data, '上传了')
            if (data) {
            } else {
            }
          })
        })
      }
    },
    // 下载图片
    down(type) {
      this.error_cc()
      // console.log('down')
      var aLink = document.createElement('a')
      aLink.download = 'author-img'
      if (type === 'blob') {
        this.$refs.cropper.getCropBlob((data) => {
          this.downImg = window.URL.createObjectURL(data)
          aLink.href = window.URL.createObjectURL(data)
          aLink.click()
        })
      } else {
        this.$refs.cropper.getCropData((data) => {
          this.downImg = data
          aLink.href = data
          aLink.click()
        })
      }
    },
    // 选择本地图片
    uploadImg(e) {
      var _this = this
      // 上传图片
      var file = e.target.files[0]
      this.imgFile = file
      _this.fileName = file.name
      if (!/\.(jpg|jpeg|png|JPG|PNG)$/.test(e.target.value)) {
        this.$message.error('图片类型必须是,jpeg,jpg,png,中的一种')
        return false
      } else if (file.size > 512000) {
        this.$message.error('图片大小必须小于500kb！')
        return false
      }
      var reader = new FileReader()
      // reader.readAsDataURL(file);
      reader.onload = (e) => {
        let data
        if (typeof e.target.result === 'object') {
          // 把Array Buffer转化为blob 如果是base64不需要
          data = window.URL.createObjectURL(new Blob([e.target.result]))
        } else {
          data = e.target.result
        }
        _this.option.img = data
      }

      // 转化为base64
      reader.readAsDataURL(file)
      // 转化为blob
      // reader.readAsArrayBuffer(file);
    },

    closeupimg() {
      this.dialogVisible = false
      // this.$refs.cropper.clearCrop() //清除截图
    }

  }

}
</script>

<style >
.info {
  width: 720px;
  margin: 0 auto;
}
.info .oper-dv {
  height: 20px;
  text-align: right;
  margin-right: 100px;
}
.info .oper-dv a {
  font-weight: 500;
}
.info .oper-dv a:last-child {
  margin-left: 30px;
}
.info .info-item {
  margin-top: 15px;
}
.info .info-item label {
  display: inline-block;
  width: 100px;
  text-align: right;
}
.info .info-item .sel-img-dv {
  position: relative;
}
.info .info-item .sel-img-dv .sel-file {
  position: absolute;
  width: 90px;
  height: 30px;
  opacity: 0;
  cursor: pointer;
  z-index: 2;
}
.info .info-item .sel-img-dv .sel-btn {
  position: absolute;
  cursor: pointer;
  z-index: 1;
}
.cropper-content {
  width: 100%;
  margin:50px auto;
  display: flex;
  flex-wrap: wrap;
  flex-direction: column;
  align-items: center;
  display: -webkit-flex;
  justify-content: space-around;
  -webkit-justify-content: space-around;
}

.cropper-content .show-preview {
  margin-top: 50px;
  flex: 1;
  -webkit-flex: 1;
  display: flex;
  display: -webkit-flex;
  justify-content: center;
  -webkit-justify-content: center;
}
.cropper-content .show-preview .preview {
  overflow: hidden;
  /* border-radius: 50%; */
  border: 1px solid #666;
  background: #ccc;
}

</style>
